#include "Core/log.h"
#include <ctime>
#include <sys/timeb.h>
#include <cstdarg>
// #include <spdlog/sinks/stdout_color_sinks.h>
// #include <spdlog/sinks/basic_file_sink.h>

#ifdef MACRO_BUILD_TYPE_RELEASE
#define MY_LOCAL_LOGFILE
#endif

#ifdef MY_LOCAL_LOGFILE
#include <fstream>
#include <iostream>
#endif

namespace CC {

	// std::shared_ptr<spdlog::logger> Log::s_CoreLogger;
	// std::shared_ptr<spdlog::logger> Log::s_ClientLogger;
    Log::LogLevel Log::m_level = Log::LogLevel_Trace;

	void Log::Init()
	{
		// std::vector<spdlog::sink_ptr> logSinks;
		// logSinks.emplace_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
		// logSinks.emplace_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("SmallEngine.log", true));

		// logSinks[0]->set_pattern("%^[%T] %n: %v%$");
		// logSinks[1]->set_pattern("[%T] [%l] %n: %v");

		// s_CoreLogger = std::make_shared<spdlog::logger>("SmallEngine", begin(logSinks), end(logSinks));
		// spdlog::register_logger(s_CoreLogger);
		// s_CoreLogger->set_level(spdlog::level::trace);
		// s_CoreLogger->flush_on(spdlog::level::trace);

		// s_ClientLogger = std::make_shared<spdlog::logger>("APP", begin(logSinks), end(logSinks));
		// spdlog::register_logger(s_ClientLogger);
		// s_ClientLogger->set_level(spdlog::level::trace);
		// s_ClientLogger->flush_on(spdlog::level::trace);
	}

    void Log::LogOut(Log::LogLevel level, const char* levelname, const char* format, ...) {
        if (level < m_level) return;

        struct timeb stTimeBuf;
        struct tm*   pCurrentTime;
        ftime(&stTimeBuf);
        pCurrentTime = localtime(&stTimeBuf.time);

        char aStr[1024] = { 0 };
        int32_t headSize = 0;

        headSize = sprintf(aStr, "%02d:%02d:%02d.%03d [%s] ",
            pCurrentTime->tm_hour, pCurrentTime->tm_min, pCurrentTime->tm_sec, stTimeBuf.millitm, levelname);

        va_list pArgs;
        va_start(pArgs, format);
        _vsnprintf(aStr + headSize, sizeof(aStr) - static_cast<size_t>(headSize), format, pArgs);
        va_end(pArgs);

#ifdef MY_LOCAL_LOGFILE
        const char* filename = "./log.txt";
        std::fstream fin;
        fin.open(filename, std::ios::app);
        std::string outstr = aStr;
        fin.write(outstr.c_str(), outstr.size());
        //fin.write("\n", 1);
        fin.close();
#else
        fprintf(stderr, "%s\r\n", aStr);
#endif

    }

    void Log::SetLogLevel(Log::LogLevel level) {
        m_level = level;
    }

    Log::LogLevel Log::GetLogLevel()
    {
        return m_level;
    }

}

